package com.dataseek.iot.device.manager.handler;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dataseek.iot.core.constant.ResponseConst;
import com.dataseek.iot.core.handler.ServiceHandler;
import com.dataseek.iot.core.response.ResponseEntity;
import com.dataseek.iot.mysql.entity.Device;
import com.dataseek.iot.mysql.entity.Product;
import com.dataseek.iot.mysql.entity.ProductParams;
import com.dataseek.iot.mysql.entity.Role;
import com.dataseek.iot.mysql.service.impl.DeviceServiceImpl;
import com.dataseek.iot.mysql.service.impl.ProductParamsServiceImpl;
import com.dataseek.iot.mysql.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author cc
 * @Title: 产品Handler
 * @Description: 产品Handler
 * @date 2021/9/199:51 上午
 * @since 1.0
 */
@Service
public class ProductHandler extends ServiceHandler<Product> {

    @Autowired
    ProductServiceImpl productService;

    @Autowired
    ProductParamsServiceImpl productParamsService;

    @Autowired
    DeviceServiceImpl deviceService;

    @Override
    public Mono<ResponseEntity> saveOne(Object entity) {
        ResponseEntity responseEntity = new ResponseEntity();
        Product product = (Product) entity;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("product_code", product.getProductCode());
        if(isExist(wrapper)){
            responseEntity.setCode(ResponseConst.DUPLICATION_CODE);
            responseEntity.setMsg("产品编码已经存在");
            responseEntity.setData(product.getProductCode());
            return Mono.just(responseEntity);
        }
        wrapper.or(true).eq("product_name", product.getProductName());
        if(isExist(wrapper)){
            responseEntity.setCode(ResponseConst.DUPLICATION_CODE);
            responseEntity.setMsg("产品名称已经存在");
            responseEntity.setData(product.getProductName());
            return Mono.just(responseEntity);
        }
       Boolean isSaved =  productService.save((Product) entity);
       return this.createResponse(isSaved);
    }

    @Override
    public Mono<ResponseEntity> saveBatch(List lists) {
        for(Object o : lists){
            Product p = (Product)o;
            ResponseEntity responseEntity = new ResponseEntity();
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("product_code", p.getProductCode());
            if(isExist(wrapper)){
                responseEntity.setCode(ResponseConst.DUPLICATION_CODE);
                responseEntity.setMsg("产品编码已经存在");
                responseEntity.setData(p.getProductCode());
                return Mono.just(responseEntity);
            }
            wrapper.or(true).eq("product_name", p.getProductName());
            if(isExist(wrapper)){
                responseEntity.setCode(ResponseConst.DUPLICATION_CODE);
                responseEntity.setMsg("产品名称已经存在");
                responseEntity.setData(p.getProductName());
                return Mono.just(responseEntity);
            }
        }
        Boolean isSaved =  productService.saveBatch(lists);
        return this.createResponse(isSaved);
    }


    @Override
    public Mono<ResponseEntity> removeById(String id) {
        ResponseEntity entity = new ResponseEntity();
        QueryWrapper queryWrapper  = new QueryWrapper();
        queryWrapper.eq("product_id", id);
        List list = deviceService.list(queryWrapper);
        if(list.size()>0) {
            entity.setCode(ResponseConst.CRUD_FAILED_CODE);
            entity.setMsg("待删除产品有设备关联，请先修改相关设备");
            entity.setData(list);
            return Mono.just(entity);
        }else {
            Boolean b = productService.removeById(id);
            return this.createResponse(b);
        }
    }

    @Override
    public Mono<ResponseEntity> removeAll(List ids) {
        ResponseEntity entity = new ResponseEntity();
        QueryWrapper queryWrapper  = new QueryWrapper();
        queryWrapper.in("product_id", ids);
        List list = deviceService.list(queryWrapper);
        if(list.size()>0){
            entity.setCode(ResponseConst.CRUD_FAILED_CODE);
            entity.setMsg("待删除产品有设备关联，请先修改相关设备");
            entity.setData(list);
            return Mono.just(entity);
        }else{
            Boolean b = productService.removeByIds(ids);
            return this.createResponse(b);
        }
    }

    @Override
    public Mono<ResponseEntity> remove(Wrapper wrapper) {
        ResponseEntity entity = new ResponseEntity();
        List<Product> products = productService.list(wrapper);
        for(Product p : products){
          String productCode  =  p.getProductCode();
          List<Device> devices = deviceService.getDeviceByProductCode(productCode);
          if(devices.size()>0){
              entity.setCode(ResponseConst.CRUD_FAILED_CODE);
              entity.setMsg("待删除产品有设备关联，请先修改相关设备");
              entity.setData(devices);
              return Mono.just(entity);
          }
        }
        Boolean isRemoved = productService.remove(wrapper);
        return this.createResponse(isRemoved);
    }

    @Override
    public Mono<ResponseEntity> remove(String id) {
        return this.removeById(id);
    }

    @Override
    public Mono<ResponseEntity> updateOne(Object entity) {
        Boolean isUpdated = productService.updateById((Product) entity);
        return this.createResponse(isUpdated);
    }

    @Override
    public Mono<ResponseEntity> update(Wrapper wrapper) {
        Boolean isUpdated = productService.update(wrapper);
        return this.createResponse(isUpdated);
    }

    @Override
    public Mono<ResponseEntity> updateBatch(List entities) {
        Boolean isUpdated = productService.updateBatchById(entities);
        return this.createResponse(isUpdated);
    }

    @Override
    public Mono<ResponseEntity> findOne(String id) {
        Product p = productService.getById(id);
        return this.createResponse(p);
    }

    @Override
    public Mono<ResponseEntity> page(Page p) {
        Page page = productService.page(p);
        return this.createResponse(page);
    }

    @Override
    public Mono<ResponseEntity> page(Page p, Wrapper wrapper) {
        Page page = productService.page(p, wrapper);
        return this.createResponse(page);
    }

    @Override
    public Flux<ResponseEntity> find(List ids) {
        List<Product> products = productService.listByIds(ids);
        return this.createResponse(products);
    }

    @Override
    public Flux<ResponseEntity> find(Wrapper wrapper) {
        List list = productService.list(wrapper);
        return this.createResponse(list);
    }

    @Override
    public Flux<ResponseEntity> findAll() {
        List list = productService.list();
        return this.createResponse(list);
    }

    @Override
    public Mono<ResponseEntity> defaultResponseOne(ResponseEntity responseEntity) {
        return Mono.just(responseEntity);
    }

    @Override
    public Flux<ResponseEntity> defaultResponseTwo(ResponseEntity responseEntity) {
        return Flux.just(responseEntity);
    }


    /**
     * 定义产品基础参数
     * @param productId
     * @param dictIds
     * @return
     */
    public Mono<ResponseEntity> definingBaseParams(String productId, List<String> dictIds){
        List<ProductParams> list = new ArrayList<>();
        ResponseEntity entity = new ResponseEntity();
        if(Objects.nonNull(dictIds)&&dictIds.size()>0){

            dictIds.forEach(new Consumer<String>() {
                ProductParams params  = new ProductParams();
                @Override
                public void accept(String s) {
                    params.setProductId(productId);
                    params.setDictId(s);
                    list.add(params);
                }
            });
        }
        Boolean b = productParamsService.saveBatch(list);
        entity.setCode(ResponseConst.CRUD_SUCCESS_CODE);
        entity.setMsg(ResponseConst.CRUD_SUCCESS);
        entity.setData(b);
        return Mono.just(entity);
    }

    /**
     * 验证是否存在
     * @param wrapper
     * @return
     */
    public Boolean isExist(QueryWrapper wrapper){
        if(Objects.nonNull(productService.getOne(wrapper))) return true;
        return false;
    }


}
